@page "/menu"
@using Menu = BootBlazorApp1.Model.Menu
@inject IDataService<Menu> DataService
@attribute [TabItemOption(Text = "菜单管理", Icon = "fa-fw fa-solid fa-desktop")]

<AdminTable TItem="Model.Menu" OnSaveAsync="OnSaveAsync" OnDeleteAsync="OnDeleteAsync"
            IsTree="true" TreeNodeConverter="TreeNodeConverter">
    <TableColumns>
        <TableColumn @bind-Field="@context.Title"></TableColumn>
        <TableColumn @bind-Field="@context.Url"></TableColumn>
        <TableColumn @bind-Field="@context.Icon"></TableColumn>
        <TableColumn @bind-Field="@context.ParentId" Visible="false" Text="父菜单">
            <EditTemplate Context="value">
                <div class="col-12 col-sm-6 col-md-6">
                <SelectTree @bind-Value="@value.ParentId" Items="MenuItems" DisplayText="父菜单"></SelectTree>
                </div>
            </EditTemplate>
        </TableColumn>
    </TableColumns>
</AdminTable>



@code {
    private List<TreeViewItem<int>> MenuItems { get; set; }= new List<TreeViewItem<int>>();
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        await RefreshMenu();
    }

    private async Task RefreshMenu()
    {
        var menus = await Menu.Select.ToListAsync();
        MenuItems.Clear();
        MenuItems.Add(new TreeViewItem<int>(0){Text = "顶级菜单"});
        MenuItems.AddRange(CascadingMenu(menus,0));
    }

    private List<TreeViewItem<int>> CascadingMenu(List<Menu> menus, int parentId) =>
        menus.Where(x => x.ParentId == parentId)
            .Select(x => new TreeViewItem<int>(x.Id) { Text = x.Title, Items = CascadingMenu(menus, x.Id) })
            .ToList();
    async Task<bool> OnSaveAsync(Menu arg1, ItemChangedType arg2)
    {
        await arg1.SaveAsync();
        await RefreshMenu();
        return true;
    }

    private async Task<bool> OnDeleteAsync(IEnumerable<Menu> arg)
    {
        if (await DataService.DeleteAsync(arg))
        {
            await RefreshMenu();
            return true;
        }

        return false;
    }

    private Task<IEnumerable<TableTreeNode<Menu>>> TreeNodeConverter(IEnumerable<Menu> items)
    {
        var ret = BuildMenuItems(items, 0);
        return Task.FromResult(ret);
        IEnumerable<TableTreeNode<Menu>> BuildMenuItems(IEnumerable<Menu> items, int parentId)
        {
            var ret = new List<TableTreeNode<Menu>>();
            ret.AddRange(items.Where(i=>i.ParentId==parentId).Select((menu,index)=> new TableTreeNode<Menu>(menu)
            {
                HasChildren = items.Any(x=>x.ParentId==menu.Id),
                //IsExpand = items.Any(x=>x.ParentId==menu.Id),
                Items = BuildMenuItems(items,menu.Id)
            }));
            return ret;
        }
    }

}